package tieba.core.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jayway.restassured.response.Cookie;

public class CommonsUtils {

	public static Map<String, String> CookieToMap(Cookie cookie) {
		Map<String, String> cookies = new HashMap<>();
		cookies.put(cookie.getName(), cookie.getValue());
		return cookies;
	}

	public static Map<String, ?> addCookie(Map<String, String> cookies,
			Cookie cookie) {
		if (cookies.containsKey(cookie.getName()))
			cookies.put(cookie.getName(), cookie.getValue());
		return cookies;
	}

	public static String regex(String regex, String body, Integer group) {
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(body);
		while (m.find()) {
			if (group != null)
				return m.group(group);
			else
				return m.group();
		}
		return null;
	}

	public static List<String> matches(String regex, String body, Integer group) {
		List<String> list = new ArrayList<>();
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(body);
		while (m.find()) {
			if (group != null)
				list.add(m.group(group));
			else
				list.add(m.group());
		}
		return list;
	}

	public static String unicodeConvert(String unistring) {
		StringBuilder sb = new StringBuilder();
		int i = -1;
		int pos = 0;
		if (unistring.indexOf("\\u", pos) == -1)
			return unistring;
		while ((i = unistring.indexOf("\\u", pos)) != -1) {
			sb.append(unistring.substring(pos, i));
			if (i + 5 < unistring.length()) {
				pos = i + 6;
				sb.append((char) Integer.parseInt(
						unistring.substring(i + 2, i + 6), 16));
			}
		}
		return sb.toString();
	}

	public static Integer getErrorCode(String body) {
		return Integer.parseInt(regex("\"error_code\":\"(\\w+)\"", body, 1));
	}
}
